﻿// Copyright (c) JosephZheng. All rights reserved. See License.txt in the project root for license

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;

namespace Lyra.Cache.Server.Interface
{
    public class ResultProcessor
    {
        public static byte[] SerializeResult(int transferCompressSize, object result)
        {
            string jsonresult = JsonConvert.SerializeObject(result);
            byte[] byteresult = null;
            byte flag = 0;
            if (jsonresult.Length >= transferCompressSize)
            {
                byteresult = GZip.Compress(Encoding.UTF8.GetBytes(jsonresult));
                flag = 8;
            }
            else
            {
                byteresult = Encoding.UTF8.GetBytes(jsonresult);
            }
            byte[] finbyteresult = new byte[byteresult.Length + 1];
            finbyteresult[0] = flag;
            Array.Copy(byteresult, 0, finbyteresult, 1, byteresult.Length);
            return finbyteresult;
        }

        public static T DeserializeResult<T>(byte[] result)
        {
            if (result != null && result.Length != 0)
            {
                string jsonresult = null;
                if (result[0] == 8)
                {
                    byte[] finbyteresult = new byte[result.Length - 1];
                    Array.Copy(result, 1, finbyteresult, 0, result.Length - 1);
                    jsonresult = Encoding.UTF8.GetString(GZip.Decompress(finbyteresult));
                }
                else if (result[0] == 0)
                {
                    jsonresult = Encoding.UTF8.GetString(result, 1, result.Length - 1);
                }
                else return default(T);
                if (!string.IsNullOrWhiteSpace(jsonresult))
                {
                    return JsonConvert.DeserializeObject<T>(jsonresult);
                }
                else return default(T);
            }
            else return default(T);
        }
    }
}
